/**
 * MonoThreadService
 * 
 */
package br.ufal.ic.sd.project.server.resources;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import br.ufal.ic.sd.project.server.core.Server_Channel;
import br.ufal.ic.sd.project.server.core.Service;
import br.ufal.ic.sd.project.server.factory.ThreadFactory;
import br.ufal.ic.sd.project.server.thread.ServerThread;

/**
 * @author keven andrade
 *
 */
public class MonoThreadService extends Server_Channel implements Service{
	
    	private ServerThread objServerThread;
    	
	/**
	 * the MonoThreadService constructor
	 * @param IntPort
	 * @throws IOException
	 */
	public MonoThreadService(int IntPort) {
		this.setIntPort(IntPort);
		
		try {
			this.objServerSocket = new ServerSocket(this.getIntPort());
		} catch (IOException e) {
//			e.printStackTrace();
			System.err.println("Ooops!");
			
		}
	}
	
	/**
	 * the MonoThreadService constructor
	 * @param socket
	 * @throws IOException
	 */
	public MonoThreadService(Socket socket) {

		try {

			this.objClientSocket = socket;
			this.objOutputStreamOut = new ObjectOutputStream(this.objClientSocket.getOutputStream());
			this.objOutputStreamOut.flush();
			this.objInputStreamIn = new ObjectInputStream(this.objClientSocket.getInputStream());

		} catch (IOException e) {
//		    e.printStackTrace();
		    System.err.println("Ooops!");
		}
	}
	
	//================================================================== getters and setters ==============================================================
	
	/**
	 * @return the objServerThread
	 */
	public ServerThread getObjServerThread() {
	    return objServerThread;
	}

	/**
	 * @param objServerThread the objServerThread to set
	 */
	public void setObjServerThread(ServerThread objServerThread) {
	    this.objServerThread = objServerThread;
	}
	
	//================================================================== Methods ==============================================================
	

	/**
	 * Accept a single connection at time
	 */
	public void runService() {
		
		System.out.println("server up!");
		System.out.println("monothread service started!");

		while(true){
			
			try {
				
				MonoThreadService objMonoThreadService = new MonoThreadService(this.objServerSocket.accept());
				
				System.out.println("Client connected!");
				
				this.objServerThread = ThreadFactory.createThread(objMonoThreadService);
				
				new Thread(this.objServerThread).start();
				
				
				
				this.objServerThread.stop();
				
	
			} catch (IOException e) {
//			    e.printStackTrace();
			    System.err.println("Ooops!");
			}
		}
		
	}

	public void stopService() {
		// TODO Auto-generated method stub
		
	}

	public void serviceSatus() {
		// TODO Auto-generated method stub
		
	}

}
